package server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author oyz
 */
public class StaticResourceUtil {


    /**
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){


        String absolutePath = StaticResourceUtil.class.getResource("/").getPath().substring(1);
        String str = absolutePath.substring(0,absolutePath.length()-1);
        return str.replaceAll("\\\\","/") + path;
    }



    /**
     * 读取静态资源输入流，通过输出流来进行输出
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while(count==0){
            count = fileInputStream.available();
        }
        int resourceSize = count;
        // 输出http请求头，然后再输出具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        // 读取内容输出
        long written = 0; // 已经读取的长度
        int byteSize = 1024; // 计划读取的长度
        byte [] bytes = new byte[byteSize];
        while (written<resourceSize){
            if(written+byteSize>resourceSize){
                byteSize = (int) (resourceSize - written); // 剩余文件长度
                bytes = new byte[byteSize];
            }
            fileInputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();

        }




    }
}
